#include "gl\glut.h"
#include <Windows.h>
#include <iostream>
#include "io.h"
#include "core/lm.h"


void SaveResult(int width, int height, char *filename) {
	
	// align to byte
	
	// allocate memory for reading screen buffer
	unsigned char *pBuff = new unsigned char [width*height*3];
	// read buffer
	glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pBuff);
	// save to bmp
	SaveBMP(pBuff, width, height, filename);

	SAFE_DELETE_ARRAY(pBuff);
}

void SaveBMP(unsigned char* data, int width, int height, char *filename) {
	BITMAPFILEHEADER head;
	BITMAPINFOHEADER info;
	int	ptr, i, j;
	unsigned char pcrgb;

	FILE *fp=fopen(filename,"wb");
	if(fp==NULL)
	{
		printf("Can't open file %s\n",filename);
		return;
	}

	head.bfType	= 0x4d42;
	head.bfSize	= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+width*height*3; 
	head.bfReserved1= 0;
	head.bfReserved2= 0;
	head.bfOffBits	= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);
	info.biSize	= sizeof(BITMAPINFOHEADER);
	info.biWidth	= width;
	info.biHeight	= height;
	info.biPlanes	= 1; 
	info.biBitCount	= 24;
	info.biCompression=0; 
	info.biSizeImage=0; 
	info.biXPelsPerMeter=0; 
	info.biYPelsPerMeter=0; 
	info.biClrUsed=0; 
	info.biClrImportant=0;
	fwrite(&head,sizeof(BITMAPFILEHEADER),1,fp);
	fwrite(&info,sizeof(BITMAPINFOHEADER),1,fp);

	ptr = 0;
	for( i = 0; i < height; i ++ )
	{
		for(j=0; j < width; j ++, ptr+= 3)
		{
			fwrite(&data[ptr+2],1,1,fp);
			fwrite(&data[ptr+1],1,1,fp);
			fwrite(&data[ptr],1,1,fp);
		}

		j = width*3;
		pcrgb=0;
		while((j%4) != 0)
		{	
			fwrite(&pcrgb,1,1,fp);
			j++;
		}
	}

	fclose(fp);

	Debug("%s was saved to bmp file\n", filename);
}